import { ref, Ref, watch } from 'vue';
import { useRouter, useRoute, RouteRecordName } from 'vue-router';
import { getTenantStyleCustomization } from '@/api/api.query.util';

// 菜单配置
export const asideList = ref([
    {
        key: '/home/service-management', // 填写路由名称，菜单关联路由
        value: '服务管理',
        icon: require('../../assets/image/home@2x.png'),
    },
    {
        key: '/home/orders-management',
        value: '订单查看',
        icon: require('../../assets/image/order@2x.png'),
    },
    {
        key: '/home/worker-management',
        value: '工人列表',
        icon: require('../../assets/image/worker@2x.png'),
    },
    {
        key: '/home/customer-management',
        value: '用户列表',
        icon: require('../../assets/image/customer@2x.png'),
    },
]);

export const routeKey: Ref<RouteRecordName> = ref('');
export const showActiveKey: Ref<RouteRecordName> = ref('');

export function handleSelect(key: string) {
    routeKey.value = key;
}

export function getTenantStyle() {
    const promise = new Promise((resolve) => {
        getTenantStyleCustomization({
            method: 'post',
            data: {},
        }).then((res) => resolve(res));
    });
    return promise;
}

export async function initTheme() {
    try {
        const res: any = await getTenantStyle();
        if (res.result) {
            const themes = {
                1: 'waterfall',
                2: 'black',
                3: 'fieryred',
                4: 'illuminating',
            };
            document.body.removeAttribute('class');
            document.getElementsByTagName('body')[0].className = `${themes[res.result.styleFlag]}_theme`;
        }
    } catch (e) {}
}

export function init() {
    const router = useRouter();
    const route = useRoute();

    watch(routeKey, (val, oVal) => {
        if (val !== oVal && asideList.value.some((e) => e.key === val)) {
            router.push({ name: val });
        }
    });

    watch(
        route,
        (val) => {
            let activeMenuKey = '';
            if (typeof val.name === 'string') {
                activeMenuKey = val.name.match(/^\/.+\/.+\//)?.[0].replace(/\/$/, '') || val.name;
            }
            showActiveKey.value = activeMenuKey;
            routeKey.value = val?.name ?? '';
        },
        {
            immediate: true,
        },
    );
}
